//
//  SQFindPasswordViewController.m
//  pai
//
//  Created by pro on 14-11-5.
//  Copyright (c) 2014年 linjunjing. All rights reserved.
//

#import "SQFindPasswordViewController.h"
#import "SQResetPasswordViewController.h"

@interface SQFindPasswordViewController ()

@end

@implementation SQFindPasswordViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitle:@"找回密码"];
    
    [self.mobileLabel addTarget:self action:@selector(moveDownTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.verificationcodeLabel addTarget:self action:@selector(moveDownTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.passwordLabel addTarget:self action:@selector(moveDownTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.againLabel addTarget:self action:@selector(moveDownTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    self.mobileLabel.delegate = self;
    self.verificationcodeLabel.delegate = self;
    self.passwordLabel.delegate = self;
    self.againLabel.delegate = self;
}
-(void)moveDownTextField:(UITextField* )text
{
    [text resignFirstResponder];
    self.view.frame = CGRectMake(0, 0, 320, 568);
}
#pragma mark - UITextField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.passwordLabel||textField == self.againLabel) {
        self.view.frame = CGRectMake(0, -100, 320, 568);
    }
    else{
        self.view.frame = CGRectMake(0, 0, 320, 568);
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    [super touchesBegan:touches withEvent:event];
    self.view.frame = CGRectMake(0, 0, 320, 568);
}
- (IBAction)doActionNext:(id)sender {
    if ([self checkInfo]) {
        user_mod_t mod;
        mod.base.msgtype = 8012;
        mod.base.len = sizeof(mod);
        mod.base.error = 0;
        
        strcpy(mod.cellphone, [self.mobileLabel.text UTF8String]);
        strcpy(mod.checkcode, [self.codeLabel.text UTF8String]);
        strcpy(mod.newpwd, [self.passwordLabel.text UTF8String]);
        
        NSMutableData* msgData = [NSMutableData data];
        [msgData appendBytes:&mod length:sizeof(mod)];
        [super sendData:msgData tag:8012 withHUD:YES];

    }
}

- (IBAction)doActionGetVerificationCode:(id)sender {
    //获取验证码
    if ([self isValidateMobile:self.mobileLabel.text]) {
        UIButton* btn = (UIButton*)sender;
        btn.enabled = NO;
        NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
        [timer fire];
        [btn setTitle:@"60" forState:UIControlStateDisabled];
        [self getVerificationCode];
    }
    else{
        UIAlertView* alterView = [[UIAlertView alloc]initWithTitle:nil message:@"手机号码输入有误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alterView show];
    }
}
-(void)getVerificationCode
{
    check_code_t check;
    check.base.msgtype = 8022;
    check.base.len = sizeof(check);
    check.base.error = 0;
    
    strcpy(check.cellphone, [self.mobileLabel.text UTF8String]);
    NSMutableData* msgData = [NSMutableData data];
    [msgData appendBytes:&check length:sizeof(check)];
    [super sendData:msgData tag:8022 withHUD:YES];
}
-(void)updateTime:(NSTimer*)timer
{
    NSInteger i = [self.codeBtn.titleLabel.text intValue];
    i--;
    if (i == 0) {
        [timer invalidate];
        timer = nil;
        self.codeBtn.enabled = YES;
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    }else{
        self.codeBtn.titleLabel.text = [NSString stringWithFormat:@"%d",i];
    }
    
}
/*手机号码验证 MODIFIED BY HELENSONG*/
-(BOOL) isValidateMobile:(NSString *)mobile
{
    if (mobile.length!=11) {
        return NO;
    }
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:mobile];
}
-(BOOL)checkInfo
{
    NSLog(@"check info");
    NSString* msg = @"";
    BOOL flag = YES;
    if (![self.passwordLabel.text isEqualToString:self.againLabel.text]) {
        msg = @"两次密码不同";
        flag = NO;
    }
    if (self.passwordLabel.text.length < 8) {
        msg = @"密码不能少于8个字符";
        flag = NO;
    }
    if ([self.passwordLabel.text isEqualToString:@""] || [self.againLabel.text isEqualToString:@""]) {
        msg = @"请输入密码";
        flag = NO;
    }
    if ([self.verificationcodeLabel.text isEqualToString:@""]) {
        msg = @"请输入短信验证码";
        flag = NO;
    }
    if (![self isValidateMobile:self.mobileLabel.text]) {
        msg = @"手机号码输入有误";
        flag = NO;
    }
    if (!flag) {
        UIAlertView* alterView = [[UIAlertView alloc]initWithTitle:nil message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alterView show];
    }
    
    return flag;
}
//读取数据
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    acs_base_t base;
    [data getBytes:&base length:sizeof(base)];
    NSString* msg = @"";
    if (base.msgtype == 8022) {
        //验证码
        if (base.error == ACS_SUCCESS) {
            msg = @"验证码已发，请注意查收！";
        }else if(base.error!=ACS_SUCCESS)
        {
            msg = @"连接出错，请重试";
        }else{
            msg = @"未知错误";
        }
    }else if (base.msgtype == 8012)
    {
        //修改密码
        if (base.error == 3050) {
            msg = @"无效的验证码";
        }else if(base.error == 3052)
        {
            msg = @"不能频繁获取验证码";
        }else if(base.error == ACS_SUCCESS)
        {
            msg = @"密码修改成功";
        }else if(base.error == 3014)
        {
            msg = @"验证码已过期";
        }else{
            msg = @"未知错误";
        }
    }
    
    if (base.msgtype == 8012 && base.error == ACS_SUCCESS) {
        [self.HUD showAnimated:YES whileExecutingBlock:^{
            self.HUD.labelText = msg;
            sleep(2);
            [self.HUD show:NO];
        } completionBlock:^{
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }
    else{
        [self.HUD showAnimated:YES whileExecutingBlock:^{
            self.HUD.labelText = msg;
            sleep(2);
            [self.HUD show:NO];
        } completionBlock:^{
        }];
    }
}
@end
